import type { FC } from 'react'
import { useMemo } from 'react'
import { Table } from 'antd'
import type { TableProps } from 'antd'
import dayjs from 'dayjs'
import { useSearchParams } from 'react-router-dom'
import BtnEditArticle from './btn-edit'
import BtnDeleteArticle from './btn-delete'
import ListIndex from './list-index'

const columns: TableProps<Article>['columns'] = [
  {
    title: '序号',
    render(_, __, index) {
      return <ListIndex index={index} />
    }
  },
  {
    title: '标题',
    dataIndex: 'title'
  },
  {
    title: '分类',
    dataIndex: 'cate_name'
  },
  {
    title: '发表时间',
    dataIndex: 'pub_date',
    render(value: string) {
      return dayjs(value).format('YYYY-MM-DD')
    }
  },
  {
    title: '状态',
    dataIndex: 'state'
  },
  {
    title: '操作',
    render(_, record) {
      return (
        <>
          <BtnEditArticle id={record.id} />
          <BtnDeleteArticle id={record.id} />
        </>
      )
    }
  }
]

// 自定义组件的 props 类型
// 需要把 URL 中解析出来的查询参数传递进来
type Props = TableProps & Partial<ArtListQuery & { total: number }>

const ArticleListTable: FC<Props> = (props) => {
  const [, setSearchParams] = useSearchParams()

  const pageOptions: TableProps['pagination'] = useMemo(() => {
    return {
      total: props.total,
      current: props.pagenum,
      pageSize: props.pagesize,
      pageSizeOptions: [2, 5, 10, 20],
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal(total) {
        return `共${total}条数据`
      },
      onChange(page, pageSize) {
        setSearchParams({ cate_id: props.cate_id, state: props.state, pagenum: page, pagesize: pageSize } as unknown as { [x: string]: string })
      }
    }
  }, [props, setSearchParams])

  return <Table {...props} columns={columns} pagination={pageOptions} />
}

export default ArticleListTable
